﻿CREATE TRIGGER [TRG_Rule_Delete]
ON  [dbo].[Rule]
INSTEAD OF DELETE
AS 
BEGIN
	SET NOCOUNT ON

	BEGIN TRY

		BEGIN TRAN

		DELETE FROM [dbo].[DataMapping]
		WHERE [RuleId] in (SELECT RuleId FROM deleted)

		DELETE FROM [dbo].[Query]
		WHERE [RuleId] in (SELECT RuleId FROM deleted)

		DELETE FROM [dbo].[Rule]
		WHERE [RuleId] in (SELECT RuleId FROM deleted)

		IF @@TRANCOUNT > 0
			COMMIT TRAN;
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
			ROLLBACK TRAN;
		THROW;
	END CATCH
END
GO
